/**
 * 协议解析
 */
module.exports=Class.extend({
  buffer:null,
  package(msg,data){
    var content=null;
    var len=8;
    if(data){
        var type=typeof(data);
        content=type=="object"?JSON.stringify(data):data;
        content=Buffer.from(content,"utf-8")
        len+=content.length;
    }
    var head=Buffer.alloc(8);
    head.writeIntLE(len,0,4);
    head.writeIntLE(msg,4,4);
    return content?Buffer.concat([head,content]):head
  },
  unPackage(data){
    if(data instanceof Buffer){
      var arr=[];
      // 追加数据
      this.buffer=this.buffer?Buffer.concat([this.buffer,data]):data;
      // 循环解包
      while(true){
          var result=this.checkProtocol();
          if(!result)break;
          arr.push(result)
          // 有异常结束
          if(result.error)break;
      }
      // 剩余包体过大
      if(this.buffer&&this.buffer.length>1024*1024*3){
        arr.push({error:2,errorMsg:"buffer cache is full",size:this.buffer.length})
      }
      return arr;
    }
    return [];
  },
  /**
     * 默认解包过程
     * 检查长度是否足够，不够则丢弃
     * @param {} data 
     */
   checkProtocol:function(){
      if(this.buffer.length<4)return null;
      const len=this.buffer.readInt32LE();
      if(len<8||len>100*1024*1024){//长度小于包头
        return {error:1,errorMsg:"package size error",size:len}
      }
      if(this.buffer.length<len)
          return null;
      const type=this.buffer.readInt32LE(4);
      const result=this.buffer.slice(8,len);
      this.buffer=this.buffer.slice(len);
      return {type,data:result}
  }
})